package com.ittx.dzt.tiktok.util;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.HmacAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class TiktokUtil {

    /***
     * 计算签名
     *
     * @param appKey
     * @param appSecret
     * @param method
     * @param params
     * @param reqBody
     * @return
     */
    public static String sign(String appKey, String appSecret, String method, Map<String, Object> params, String reqBody) {
        // 按给定规则拼接参数
        StringBuilder str = new StringBuilder();
        str.append(appSecret);
        str.append(method);
        TreeMap<String, Object> treeMap = new TreeMap<>(params);
        for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
            str.append(entry.getKey()).append(entry.getValue());
        }
        if (StringUtils.isNotBlank(reqBody))
            str.append(reqBody);
        str.append(appSecret);
        log.debug(str.toString());
        return DigestUtil.hmac(HmacAlgorithm.HmacSHA256, appSecret.getBytes(StandardCharsets.UTF_8)).digestHex(str.toString());
    }

    /**
     * 从扩展字段取值
     *
     * @param ext
     * @param identifier
     * @return
     */
    public static Object getExtendValue(Map<String, Object> ext, String identifier) {
        if (ext == null)
            return null;
        return ext.get(identifier);
    }

}
